
<template>
	<view class="container">
		<image class="banner" src="/static/svg/wrong-questions.svg" mode="widthFix"></image>
		<!-- 错题列表 -->
		<view v-if="wrongQuestions.length > 0">
			<uni-swipe-action>
				<uni-swipe-action-item 
					v-for="(item, index) in wrongQuestions" 
					:key="item.id"
					:right-options="swipeOptions"
					@click="handleSwipeClick($event, item)"
				>
					<uni-card :is-shadow="true" margin="10px 0">
						<!-- 错题头部信息 -->
						<view class="wrong-header">
							<view class="wrong-info">
								<text class="wrong-count">错误 {{ item.wrongCount }} 次</text>
								<uni-dateformat 
									v-if="item.lastWrongTime"
									:date="item.lastWrongTime" 
									format="yyyy-MM-dd HH:mm"
									class="wrong-time"
								></uni-dateformat>
							</view>
						</view>
						
						<!-- 题目内容 -->
						<view v-if="item.questionDetail" class="question-section">
							<view class="question-title">题目：</view>
							<text class="question-text">{{ item.questionDetail.question }}</text>
							
							<!-- 选项 -->
							<view class="options-section">
								<view 
									v-for="(option, optIndex) in item.questionDetail.options" 
									:key="optIndex"
									class="option-item"
									:class="{'correct-option': option.optionKey === item.questionDetail.answer}"
								>
									<text class="option-label">{{ option.optionKey }}.</text>
									<text class="option-text">{{ option.optionValue }}</text>
									<text v-if="option.optionKey === item.questionDetail.answer" class="answer-tag">正确答案</text>
								</view>
							</view>
							
							<!-- 解析 -->
							<view class="explanation-section">
								<text class="explanation-title">解析：</text>
								<text class="explanation-text">{{ item.questionDetail.explanation || '暂无解析' }}</text>
							</view>
						</view>
						
						<!-- 加载题目详情中 -->
						<view v-else class="loading-detail">
							<text>加载题目详情中...</text>
						</view>
					</uni-card>
				</uni-swipe-action-item>
				</uni-swipe-action>
				
				<!-- 加载更多 -->
				<uni-load-more 
					:status="loadMoreStatus" 
					@clickLoadMore="loadMore"
				></uni-load-more>
			</view>
		
		<!-- 空状态 -->
		<view v-else-if="!loading" class="empty">
			<text>暂无错题</text>
		</view>
		
		<!-- 加载中 -->
		<view v-if="loading && wrongQuestions.length === 0" class="loading">
			<text>加载中...</text>
		</view>
	</view>
</template>

<script>
import { get, del } from '@/utils/api.js'

export default {
	data() {
		return {
			wrongQuestions: [], // 错题列表
			allQuestions: [], // 所有题目（用于匹配题目详情）
			loading: false,
			loadMoreStatus: 'more', // more | loading | noMore
			currentPage: 1,
			pageSize: 10,
			hasLoaded: false, // 标记是否已经加载过数据
			swipeOptions: [
				{
					text: '删除',
					style: {
						backgroundColor: '#ff3b30'
					}
				}
			]
		}
	},
	onLoad() {
		this.loadAllQuestions()
		this.loadWrongQuestions()
	},
	onShow() {
		// 切换到错题本页面时，如果已经加载过数据，则刷新数据
		if (this.hasLoaded) {
			this.refreshData()
		}
	},
	onPullDownRefresh() {
		this.currentPage = 1
		this.wrongQuestions = []
		this.loadWrongQuestions().finally(() => {
			uni.stopPullDownRefresh()
		})
	},
	methods: {
		// 刷新数据（重置分页并重新加载）
		refreshData() {
			this.currentPage = 1
			this.wrongQuestions = []
			this.loadMoreStatus = 'more'
			// 重新加载题目列表（可能题目有更新）
			this.loadAllQuestions()
			// 重新加载错题列表
			this.loadWrongQuestions()
		},
		
		// 加载所有题目（用于匹配题目详情）
		async loadAllQuestions() {
			try {
				const data = await get('/practice/questions')
				this.allQuestions = data || []
			} catch (error) {
				console.error('加载题目列表失败:', error)
			}
		},
		
		// 加载错题列表
		async loadWrongQuestions() {
			// 如果是第一页且正在加载，允许继续（用于刷新）
			if (this.currentPage > 1 && (this.loadMoreStatus === 'loading' || this.loadMoreStatus === 'noMore')) {
				return
			}
			
			this.loading = this.currentPage === 1
			this.loadMoreStatus = 'loading'
			
			try {
				const data = await get('/practice/wrong-questions', {
					pageNum: this.currentPage,
					pageSize: this.pageSize
				})
				
				if (data && data.records) {
					const newQuestions = data.records || []
					
					// 合并题目详情
					newQuestions.forEach(item => {
						const questionDetail = this.allQuestions.find(q => q.id === item.questionId)
						if (questionDetail) {
							item.questionDetail = questionDetail
						}
					})
					
					if (this.currentPage === 1) {
						this.wrongQuestions = newQuestions
					} else {
						this.wrongQuestions = [...this.wrongQuestions, ...newQuestions]
					}
					
					// 判断是否还有更多
					if (newQuestions.length < this.pageSize || this.wrongQuestions.length >= data.total) {
						this.loadMoreStatus = 'noMore'
					} else {
						this.loadMoreStatus = 'more'
					}
				} else {
					this.loadMoreStatus = 'noMore'
				}
			} catch (error) {
				console.error('加载错题列表失败:', error)
				this.loadMoreStatus = 'more'
			} finally {
				this.loading = false
				// 标记已加载过数据
				this.hasLoaded = true
			}
		},
		
		// 加载更多
		loadMore() {
			if (this.loadMoreStatus === 'more') {
				this.currentPage++
				this.loadWrongQuestions()
			}
		},
		
		// 滑动操作点击
		handleSwipeClick(e, item) {
			if (e.index === 0) {
				// 删除错题
				uni.showModal({
					title: '提示',
					content: '确定要删除这条错题吗？',
					success: (res) => {
						if (res.confirm) {
							this.deleteWrongQuestion(item.id)
						}
					}
				})
			}
		},
		
		// 删除错题
		async deleteWrongQuestion(id) {
			try {
				await del(`/practice/wrong-questions/${id}`)
				uni.showToast({
					title: '删除成功',
					icon: 'success'
				})
				// 重新加载列表
				this.currentPage = 1
				this.wrongQuestions = []
				this.loadWrongQuestions()
			} catch (error) {
				console.error('删除错题失败:', error)
				uni.showToast({
					title: '删除失败',
					icon: 'none'
				})
			}
		}
	}
}
</script>

<style lang="scss" scoped>
@import '@/styles/theme.scss';
.container {
	min-height: 100vh;
	background-color: #F9FAFB;
	padding: 10px;
}

.wrong-header {
	margin-bottom: 15px;
	padding-bottom: 10px;
	border-bottom: 1px solid #eee;
}

.wrong-info {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.wrong-count {
	font-size: 14px;
	color: #FF7F50;
	font-weight: bold;
}

.wrong-time {
	font-size: 12px;
	color: #999;
}

.question-section {
	margin-top: 10px;
}

.question-title {
	font-size: 15px;
	font-weight: bold;
	color: #333;
	margin-bottom: 8px;
}

.question-text {
	font-size: 15px;
	line-height: 1.6;
	color: #333;
	display: block;
	margin-bottom: 15px;
}

.options-section {
	margin-top: 10px;
	margin-bottom: 15px;
}

.option-item {
	display: flex;
	align-items: center;
	padding: 8px 0;
	border-bottom: 1px solid #f0f0f0;
}

.option-item:last-child {
	border-bottom: none;
}

.option-item.correct-option {
	background-color: #f0fff4;
	padding: 8px;
	border-radius: 4px;
	margin-bottom: 5px;
}

.option-label {
	font-weight: bold;
	margin-right: 8px;
	color: #333;
	min-width: 20px;
}

.option-text {
	flex: 1;
	font-size: 14px;
	color: #666;
}

.answer-tag {
	font-size: 12px;
	color: #20B2AA;
	background-color: #f0fff4;
	padding: 2px 8px;
	border-radius: 4px;
	margin-left: 8px;
}

.explanation-section {
	margin-top: 15px;
	padding-top: 15px;
	border-top: 1px solid #eee;
}

.explanation-title {
	font-size: 14px;
	font-weight: bold;
	color: #333;
	margin-bottom: 8px;
	display: block;
}

.explanation-text {
	font-size: 14px;
	line-height: 1.6;
	color: #666;
	display: block;
}

.loading-detail {
	text-align: center;
	padding: 20px;
	color: #999;
	font-size: 14px;
}

.loading, .empty {
	text-align: center;
	padding: 40px 20px;
	color: #999;
}
</style>

